package com.beta.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.beta.entity.Orders;
import com.beta.service.IDateTimeService;
import com.beta.service.IOrderOperateService;
import com.beta.service.IOrdersService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.Duration;
import java.util.Date;
import java.util.List;

/**
 * Created by vector on 2017/1/12.
 */
public class OrderAutoConfirmReceiptJob implements SimpleJob {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IDateTimeService dateTimeService;
    @Autowired
    private IOrderOperateService orderOperateService;
    @Autowired
    private IOrdersService ordersService;

    private static final Long DEFAULT_ORDER_AUTO_CONFIRM_RECEIPT_MINUTES = 7L * 24 * 60; // 默认值为7天

    @Override
    public void execute(ShardingContext shardingContext) {
        logger.info("订单自动确认收货定时任务 - 开始");

        List<Orders> pickedButNotReceiptOrders = getPickedButNotReceiptOrders(shardingContext);
        if (CollectionUtils.isNotEmpty(pickedButNotReceiptOrders)) {
            pickedButNotReceiptOrders.forEach(order -> {
                orderOperateService.executeReceiptConfirm(order.getId());
            });
        }

        logger.info("订单自动确认收货定时任务 - 结束");
    }

    private List<Orders> getPickedButNotReceiptOrders(ShardingContext shardingContext) {
        Long orderAutoConfirmReceiptMinutes = getOrderAutoConfirmReceiptMinutes(shardingContext);
        Date dbDate = dateTimeService.toDbDate();
        Date beforePickedDate = Date.from(dbDate.toInstant().minus(Duration.ofMinutes(orderAutoConfirmReceiptMinutes)));
        return ordersService.getPickedButNotReceiptOrders(beforePickedDate);
    }

    private Long getOrderAutoConfirmReceiptMinutes(ShardingContext shardingContext) {
        if (StringUtils.isBlank(shardingContext.getJobParameter())) {
            warnNoAutoConfirmReceiptConfig();
            return DEFAULT_ORDER_AUTO_CONFIRM_RECEIPT_MINUTES;
        }

        try {
            return Long.parseLong(shardingContext.getJobParameter());
        } catch (Exception e) {
            warnNoAutoConfirmReceiptConfig();
            return DEFAULT_ORDER_AUTO_CONFIRM_RECEIPT_MINUTES;
        }
    }

    private void warnNoAutoConfirmReceiptConfig() {
        logger.warn("订单自动确认收货定时任务 - 警告: 未配置订单自动收货确认时间，使用默认配置 - minutes={}", DEFAULT_ORDER_AUTO_CONFIRM_RECEIPT_MINUTES);
    }

}
